package com.neteast.androidclient.contact.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.text.TextUtils;
import android.util.Log;
import com.neteast.androidclient.contact.Constant;
import com.neteast.androidclient.contact.domain.Contact;
import com.neteast.androidclient.contact.domain.ContactData;


public class ContactsUtils {
	
	private static final String TAG = "test";
	/**
	 * 获取所有联系人
	 * @param ctx
	 * @return
	 */
	public static Cursor getAllContacts(Context ctx){
		Cursor people = null;
		try{
			String[] projection = {Contacts._ID,Contacts.DISPLAY_NAME};
			people = ctx.getContentResolver().query(Contacts.CONTENT_URI, projection, null, null, null);
		}
		catch(Exception e){
			Log.e(TAG, e.getMessage());
		}
		return people;
	}
	/**
	 * 获取联系人的姓名
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static String getDisplayName(Context ctx, String _id){
		String name = "";
		Cursor mCur = null;
		try{
			mCur = ctx.getContentResolver().query(
					Contacts.CONTENT_URI,
					null, 
					Contacts._ID + " = ?", 
					new String[]{_id}, 
					null);
			if (mCur.moveToFirst()) {
				name = mCur.getString(mCur.getColumnIndex(Contacts.DISPLAY_NAME));
			}
		}
		catch(Exception e){
			Log.e(TAG, e.getMessage());
		}
		finally{
			mCur.close();
		}
		return name;
	}
	public static char getSortKey(Context ctx, String _id){
		String name = "";
		Cursor mCur = null;
		try{
			mCur = ctx.getContentResolver().query(
					Contacts.CONTENT_URI,
					new String[]{"sort_key"}, 
					Contacts._ID + " = ?", 
					new String[]{_id}, 
					null);
			if (mCur.moveToFirst()) {
				name = mCur.getString(0);
			}
		}
		catch(Exception e){
			Log.e(TAG, e.getMessage());
		}
		finally{
			mCur.close();
		}
		char sorykey='A';
		if (!TextUtils.isEmpty(name)) {
			sorykey=Character.toUpperCase(name.charAt(0));
		}
		return sorykey;
	}
	/**
	 * 获取联系人所有的电话信息
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static ArrayList<ContactData> getPersonPhoneNumber(Context ctx, String _id) {
		ArrayList<ContactData> phones = null;
		Cursor mCur = null;
		try{
			
			mCur = ctx.getContentResolver().query(
					Phone.CONTENT_URI, 
					null, 
					Phone.CONTACT_ID + " = ?", 
					new String[]{_id}, 
					null);
			if(mCur.moveToFirst()){
				phones = new ArrayList<ContactData>();
				do{
					ContactData p = new ContactData();
					p.mimeTypeId=Constant.MIME_PHONE;
					p.modified=Constant.CONTACT_NEW;
					p.content=mCur.getString(mCur.getColumnIndex(Phone.NUMBER));
					String type = mCur.getString(mCur.getColumnIndex(Phone.TYPE));
					switch(Integer.valueOf(type)){
						case Phone.TYPE_ASSISTANT:
							p.label="其他";
							break;
						case Phone.TYPE_CALLBACK:
							p.label="其他";
							break;
						case Phone.TYPE_CAR:
							p.label="车载电话";
							break;
						case Phone.TYPE_COMPANY_MAIN:
							p.label="总机";
							break;
						case Phone.TYPE_FAX_HOME:
							p.label="家庭传真";
							break;
						case Phone.TYPE_FAX_WORK:
							p.label="工作传真";
							break;
						case Phone.TYPE_HOME:
							p.label="家庭";
							break;
						case Phone.TYPE_ISDN:
							p.label="其他";
							break;
						case Phone.TYPE_MAIN:
							p.label="总机";
							break;
						case Phone.TYPE_MMS:
							p.label="其他";
							break;
						case Phone.TYPE_MOBILE:
							p.label="手机";
							break;
						case Phone.TYPE_OTHER:
							p.label="其他";
							break;
						case Phone.TYPE_OTHER_FAX:
							p.label="传真";
							break;
						case Phone.TYPE_PAGER:
							p.label="寻呼机";
							break;
						case Phone.TYPE_RADIO:
							p.label="其他";
							break;
						case Phone.TYPE_TELEX:
							p.label="电报";
							break;
						case Phone.TYPE_TTY_TDD:
							p.label="其他";
							break;
						case Phone.TYPE_WORK:
							p.label="工作";
							break;
						case Phone.TYPE_WORK_MOBILE:
							p.label="工作手机";
							break;
						case Phone.TYPE_WORK_PAGER:
							p.label="电报";
							break;
						case Phone.TYPE_CUSTOM:
							p.label="自定义";
							break;
						default:
							p.label="家庭";
							break;
					}
					if (p.label.equals("自定义")) {
						p.label=mCur.getString(mCur.getColumnIndex(Phone.DATA3));
					}
					phones.add(p);
				}
				while(mCur.moveToNext());
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception finding phone numbers " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return phones;
	}
	/**
	 * 获取联系人的email信息
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static ArrayList<ContactData> getPersonEmail(Context ctx, String _id) {
		ArrayList<ContactData> email = null;
		Cursor mCur = null;
		try{
			mCur = ctx.getContentResolver().query(
					Email.CONTENT_URI, 
					null, 
					Email.CONTACT_ID + " = ?", 
					new String[]{_id},
					null);
			if(mCur.moveToFirst()){
				email = new ArrayList<ContactData>();
				do{
					ContactData e = new ContactData();
					e.mimeTypeId=Constant.MIME_EMAIL;
					e.modified=Constant.CONTACT_NEW;
					e.content=mCur.getString(mCur.getColumnIndex(Email.DATA));
					String type = mCur.getString(mCur.getColumnIndex(Email.TYPE));
					switch(Integer.valueOf(type)){
						case Email.TYPE_HOME:
							e.label="家庭";
							break;
						case Email.TYPE_MOBILE:
							e.label="移动";
							break;
						case Email.TYPE_WORK:
							e.label="工作";
							break;
						case Email.TYPE_CUSTOM:
							e.label="自定义";
							break;
						default:
							e.label="其他";
							break;
					}
					if (e.label.equals("自定义")) {
						e.label=mCur.getString(mCur.getColumnIndex(Email.DATA3));
					}
					email.add(e);
				}
				while(mCur.moveToNext());
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception finding emails " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return email;
	}
	/**
	 * 获取联系人的即时通讯信息
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static ArrayList<ContactData> getPersonIM(Context ctx, String _id){
		ArrayList<ContactData> im = null;
		Cursor mCur = null;
		try{
			String whereClause = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ?";
			String[] params = new String[]{_id, Im.CONTENT_ITEM_TYPE};
			mCur = ctx.getContentResolver().query(
					Data.CONTENT_URI, 
					null, 
					whereClause, 
					params, 
					null);
			if(mCur.moveToFirst()){
				im = new ArrayList<ContactData>();
				do{
					ContactData i = new ContactData();
					i.mimeTypeId=Constant.MIME_IM;
					i.modified=Constant.CONTACT_NEW;
					i.content=mCur.getString(mCur.getColumnIndex(Im.DATA));
					String type = mCur.getString(mCur.getColumnIndex(Im.PROTOCOL));
					switch(Integer.valueOf(type)){
						case Im.PROTOCOL_AIM:
							i.label="AIM";
							break;
						case Im.PROTOCOL_GOOGLE_TALK:
							i.label="GTalk";
							break;
						case Im.PROTOCOL_ICQ:
							i.label="ICQ";
							break;
						case Im.PROTOCOL_JABBER:
							i.label="JABBER";
							break;
						case Im.PROTOCOL_MSN:
							i.label="MSN";
							break;
						case Im.PROTOCOL_NETMEETING:
							i.label="Net Meeting";
							break;
						case Im.PROTOCOL_QQ:
							i.label="QQ";
							break;
						case Im.PROTOCOL_SKYPE:
							i.label="Skype";
							break;
						case Im.PROTOCOL_YAHOO:
							i.label="Yahoo";
							break;
						default:
							i.label="自定义";
							break;
					}
					if (i.label.equals("自定义")) {
						i.label=mCur.getString(mCur.getColumnIndex(Im.DATA6));
					}
					im.add(i);
				}
				while(mCur.moveToNext());
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception in getPersonIm() " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return im;
	}
	/**
	 * 获取联系人的地址信息
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static ArrayList<ContactData> getPersonAddress(Context ctx, String _id){
		ArrayList<ContactData> address = null;
		Cursor mCur = null;
		try{
			mCur = ctx.getContentResolver().query(
					StructuredPostal.CONTENT_URI, 
					null, 
					StructuredPostal.CONTACT_ID + " = ?", 
					new String[]{_id}, 
					null);
			if(mCur.moveToFirst()){
				address = new ArrayList<ContactData>();
				do{
					ContactData add=new ContactData();
					add.modified=Constant.CONTACT_NEW;
					add.mimeTypeId=Constant.MIME_LOCATION;
					add.content=mCur.getString(mCur.getColumnIndex(StructuredPostal.FORMATTED_ADDRESS));
					String type = mCur.getString(mCur.getColumnIndex(StructuredPostal.TYPE));
					String t = "";
					switch(Integer.valueOf(type)){
						case StructuredPostal.TYPE_HOME:
							t = "家庭";
							break;
						case StructuredPostal.TYPE_WORK:
							t = "公司";
							break;
						case StructuredPostal.TYPE_OTHER:
							t = "其他";
							break;
						case StructuredPostal.TYPE_CUSTOM:
							t = "自定义";
							break;
						default:
							t = "其他";
							break;
					}
					add.label=t;
					if (add.label.equals("自定义")) {
						add.label=mCur.getString(mCur.getColumnIndex(StructuredPostal.DATA3));
					}
					address.add(add);
				}
				while(mCur.moveToNext());
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception in getAddress() " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return address;
	}
	/**
	 * 获取联系人的公司和职位
	 * @param ctx
	 * @param _id
	 * @return String[0] 为公司， String[1] 为职位 
	 */
	public static String[] getPersonOrg(Context ctx,String _id){
		String[] org = null;
		Cursor mCur = null;
		try{
			String whereClause = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ?";
			String[] params = new String[]{_id, Organization.CONTENT_ITEM_TYPE};
			mCur = ctx.getContentResolver().query(Data.CONTENT_URI, null, whereClause, params, null);
			if(mCur.moveToFirst()){
				org = new String[2];
				String orgName = mCur.getString(mCur.getColumnIndex(Organization.DATA));
				String title = mCur.getString(mCur.getColumnIndex(Organization.TITLE));
				org[0]=orgName;
				org[1]=title;
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception in getPersonOrg() " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return org;
	}
	/**
	 * 获取昵称
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static String getPersonNickName(Context ctx,String _id){
		String nickName = null;
		Cursor mCur = null;
		try{
			String whereClause = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ?";
			String[] params = new String[]{_id, Nickname.CONTENT_ITEM_TYPE};
			mCur = ctx.getContentResolver().query(Data.CONTENT_URI, null, whereClause, params, null);
			if(mCur.moveToFirst()){
				nickName = mCur.getString(mCur.getColumnIndex(Nickname.DATA));
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception in getPersonOrg() " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return nickName;
	}
	/**
	 * 获取联系人的备注信息
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static String getPersonRemark(Context ctx,String _id){
		String note = null;
		Cursor mCur = null;
		try{
			String whereClause = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ?";
			String[] params = new String[]{_id, Note.CONTENT_ITEM_TYPE};
			mCur = ctx.getContentResolver().query(Data.CONTENT_URI, null, whereClause, params, null);
			if(mCur.moveToFirst()){
				note = mCur.getString(mCur.getColumnIndex(Note.NOTE));
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception in getPersonOrg() " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return note;
	}
	/**
	 * 获取所有的分组信息
	 * @param ctx
	 * @return HashMap key为分组id，value为组名
	 */
	public static HashMap<String, String> getAllGroups(Context ctx){
		Cursor mCur = null;
		HashMap<String, String> groups=null;
		
		try{
			String whereClause=Groups.DIRTY+"= 0 AND "+Groups.GROUP_VISIBLE+" =0";
			mCur = ctx.getContentResolver().query(Groups.CONTENT_URI, null,whereClause, null, null);
			if(mCur.moveToFirst()){
				groups=new HashMap<String,String>();
				do {
					groups.put(mCur.getString(mCur.getColumnIndex(Groups._ID)),
							mCur.getString(mCur.getColumnIndex(Groups.TITLE)));
				} while (mCur.moveToNext());
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception in getPersonOrg() " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return groups;
	}
	/**
	 * 获取一个联系人在哪几个组里
	 * @param ctx
	 * @param _id
	 * @return ArrayList<String> 分组id的集合
	 */
	public static ArrayList<String> getGroupMembership(Context ctx,String _id){
		ArrayList<String> groupMembership=null;
		Cursor mCur = null;
		try{
			mCur = ctx.getContentResolver().query(Data.CONTENT_URI,
					new String[]{Data.DATA1},
					Data.CONTACT_ID+" =? AND "+Data.MIMETYPE+" =? ", 
					new String[]{_id,GroupMembership.CONTENT_ITEM_TYPE},
					null);
			if(mCur.moveToFirst()){
				groupMembership=new ArrayList<String>();
				do {
					groupMembership.add(mCur.getString(0));
				} while (mCur.moveToNext());
			}
		}
		catch(Exception e){
			Log.e(TAG, "Exception in getPersonOrg() " + e.getMessage());
		}
		finally{
			mCur.close();
		}
		return groupMembership;
	}

	/**
	 * 获取联系人的照片，存储在sd卡photo文件夹里，文件名称为_id.png
	 * @param ctx
	 * @param _id
	 * @return 返回照片存储文件的绝对路径
	 */
	public static String getPersonPhoto(Context ctx,String _id){
		Cursor mCur=null;
		String photo=null;
		try {
			mCur=ctx.getContentResolver().query(
					Contacts.CONTENT_URI, 
					new String[]{Contacts.PHOTO_ID}, 
					Contacts._ID+" =? ", 
					new String[]{_id}, 
					null);
			if (mCur.moveToFirst()) {
				if (mCur.getLong(0)>0) {
					Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(_id));
					InputStream inputStream = Contacts.openContactPhotoInputStream(ctx.getContentResolver(), uri);
					if (inputStream!=null) {
						Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
						File photoFile = FileUtil.createPhotoFile(ctx);
						FileOutputStream fos=new FileOutputStream(photoFile);
						bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
						photo=photoFile.getAbsolutePath();
						fos.close();
						bitmap.recycle();
					}
				}
			}
		} catch (Exception e) {
			Log.e(TAG, "Exception in getPersonPhoto() " + e.getMessage());
		}finally{
			mCur.close();
		}
		return photo;
	}
	
	/**
	 * 填充联系人
	 * @param ctx
	 * @param _id
	 * @return
	 */
	public static Contact populateContact(Context ctx, String _id){
		Contact contact = null;
		try{
			contact = new Contact();
			contact.localId=_id;
			contact.ownId=LoginUtil.getLastLoginUserId(ctx);
			contact.displayName=getDisplayName(ctx, _id);
			contact.sortKey=getSortKey(ctx, _id);
			contact.isReadOnly=false;
			String[] org = getPersonOrg(ctx, _id);
			if (org!=null) {
				contact.organization=org[0];
				contact.job=org[1];
			}
			ArrayList<ContactData> phones = getPersonPhoneNumber(ctx, _id);
			if (phones!=null) {
				int size = phones.size();
				for(int i=0;i<size;i++){
					String phone=ValidateUtil.formatMobilePhone(phones.get(i).content);
					if (i==0&&ValidateUtil.validatePhone("手机", phone)) {
						contact.fphone=phone;
					}else if (i==1&&ValidateUtil.validatePhone("手机", phone)){
						contact.fphone=phone;
					}else {
						contact.phones.add(phones.get(i));
					}
				}
			}
			ArrayList<ContactData> emails = getPersonEmail(ctx, _id);
			if (emails!=null) {
				int size = emails.size();
				for(int i=0;i<size;i++){
					String email=emails.get(i).content;
					if (i==0&&ValidateUtil.validateEmail(email)){
						contact.femail=email;
					}else if (i==1&&ValidateUtil.validateEmail(email)) {
						contact.femail=email;
					}else {
						contact.emails.add(emails.get(i));
					}
				}
			}
			ArrayList<ContactData> ims = getPersonIM(ctx, _id);
			if (ims!=null) {
				contact.ims.addAll(ims);
			}
			ArrayList<ContactData> locations = getPersonAddress(ctx, _id);
			if (locations!=null) {
				contact.locations.addAll(locations);
			}
			contact.hasPhoto=false;
			String photo = getPersonPhoto(ctx, _id);
			if (!TextUtils.isEmpty(photo)) {
				contact.photo=photo;
				contact.hasPhoto=true;
			}
			contact.remark=getPersonRemark(ctx, _id);
		}
		catch(Exception e){
			Log.e(TAG, "Exception populating contact bean " + e.getMessage());
		}
		return contact;
	}
	
	/**
	 * 验证ArrayList不为空，如果不为空而且长度不为0，返回true
	 * 如果为空或者长度为0，返回false
	 * @param str
	 * @return
	 */
	public static boolean validateIsNotNull(List<Contact> list)
	{
		if(list != null && list.size() !=0)
		{
			return true;
		}
		return false;
	}
	
	public static String getCurrentData(){
        Calendar c = Calendar.getInstance();
        String mYear = c.get(Calendar.YEAR)+""; 
        String mMonth = (c.get(Calendar.MONTH)+1)+"";//获取当前月份
        String mDay = c.get(Calendar.DAY_OF_MONTH)+"";//获取当前月份的日期号码
        String mHour = c.get(Calendar.HOUR_OF_DAY)+"";
        String mMin = c.get(Calendar.MINUTE)+"";
        String mSec = c.get(Calendar.SECOND)+"";
        return mYear+"-"+mMonth+"-"+mDay+"_"+mHour+":"+mMin+":"+mSec;
	}
}
